from PyQt5.QtGui import QMovie
from loguru import logger
from PyQt5.QtCore import Qt, QPoint, QVariant
from PyQt5.QtWidgets import QTreeWidget, QTreeWidgetItem, QVBoxLayout, QWidget, QMenu, QAction, QPushButton, \
    QDialog, QLineEdit, QLabel, QMessageBox, QCheckBox, QHBoxLayout, QHeaderView


class TenantTree(QWidget):
    def __init__(self, main_content_area):
        super().__init__()
        self.main_content_area = main_content_area
        self.tree = QTreeWidget()
        self.tree.setHeaderHidden(True)  # 隐藏头部
        self.tree.setMinimumHeight(100)
        self.tree.setContextMenuPolicy(Qt.CustomContextMenu)
        self.tree.setColumnWidth(1, 300)

        # 设置样式表，使边框更窄，内容超出时显示滚动条
        self.tree.setStyleSheet("""
            QTreeWidget {
                border: none;
                padding: 0px;
            }
            QTreeWidget::item {
                padding: 0px;
            }
        """)

        self.tree.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        self.tree.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)

        # 确保列宽自动调整以适应内容
        self.tree.header().setSectionResizeMode(QHeaderView.ResizeToContents)
        self.tree.header().setStretchLastSection(False)

        layout = QVBoxLayout()
        layout.addWidget(self.tree)
        layout.setContentsMargins(0, 0, 0, 0)  # 设置边距为 0
        layout.setSpacing(0)  # 设置组件之间的间距为 0
        self.setLayout(layout)
        self.current_tenant_service = None

        self.tree.customContextMenuRequested.connect(self.show_context_menu)
        self.tree.setColumnCount(1)
        # self.tree.setHeaderLabels(['Tenants','row'])
        self.tree.itemDoubleClicked.connect(self.on_item_double_clicked)

    def refresh(self, tenant_service):
        self.tree.clear()
        self.current_tenant_service = tenant_service
        # 获取所有 tenants
        tenants = self.current_tenant_service.get_tenant_list()
        for tenant in tenants:
            tenant_item = QTreeWidgetItem(self.tree)
            tenant_item.setText(0, tenant.name)
            tenant_item.setData(0, Qt.UserRole, "tenant")
        self.tree.expandAll()  # 展开所有节点

    def show_context_menu(self, pos: QPoint):
        item = self.tree.itemAt(pos)
        menu = QMenu(self)

        if item:
            # 节点上右击弹出的菜单
            add_action = QAction("新增", self)
            delete_action = QAction("删除", self)
            menu.addAction(add_action)
            menu.addAction(delete_action)
            add_action.triggered.connect(self.add_tenant)
            delete_action.triggered.connect(self.delete_tenant)
        else:
            # 空白处右击弹出的菜单
            add_action = QAction("新增", self)
            menu.addAction(add_action)
            add_action.triggered.connect(self.add_tenant)

        menu.exec_(self.tree.mapToGlobal(pos))

    def add_tenant(self):
        dialog = QDialog(self)
        dialog.setWindowTitle("新增租户")

        layout = QVBoxLayout()
        label = QLabel("请输入租户名称 (仅允许英文, 数字, 及 -_ 符号):")
        layout.addWidget(label)
        self.tenant_name_input = QLineEdit()
        layout.addWidget(self.tenant_name_input)
        button_layout = QVBoxLayout()
        ok_button = QPushButton("确定")
        ok_button.clicked.connect(lambda: self.validate_and_add_tenant(dialog))
        button_layout.addWidget(ok_button)
        cancel_button = QPushButton("取消")
        cancel_button.clicked.connect(dialog.reject)
        button_layout.addWidget(cancel_button)
        layout.addLayout(button_layout)
        dialog.setLayout(layout)
        dialog.exec_()

    def validate_and_add_tenant(self, dialog):
        tenant_name = self.tenant_name_input.text().strip()
        clus = self.current_tenant_service.get_clusters()
        self.current_tenant_service.add_tenant(tenant_name, clus)
        self.refresh(self.current_tenant_service)
        dialog.accept()

    def delete_tenant(self):
        item = self.tree.currentItem()
        if item is None:
            QMessageBox.warning(self, "操作错误", "请先选择一个租户进行删除")
            return

        tenant_name = item.text(0)
        dialog = QDialog(self)
        dialog.setWindowTitle("删除租户")

        layout = QVBoxLayout()

        label = QLabel(f"确定要删除租户: {tenant_name} 吗？")
        layout.addWidget(label)

        self.force_delete_checkbox = QCheckBox("是否强制删除")
        layout.addWidget(self.force_delete_checkbox)

        button_layout = QHBoxLayout()

        cancel_button = QPushButton("取消")
        cancel_button.clicked.connect(dialog.reject)
        button_layout.addWidget(cancel_button)

        delete_button = QPushButton("确认")
        delete_button.setStyleSheet("background-color: red; color: white;")
        delete_button.clicked.connect(lambda: self.confirm_delete_tenant(dialog, tenant_name))
        button_layout.addWidget(delete_button)

        layout.addLayout(button_layout)
        dialog.setLayout(layout)

        dialog.exec_()

    def confirm_delete_tenant(self, dialog, tenant_name):
        force_delete = self.force_delete_checkbox.isChecked()

        succ = self.current_tenant_service.delete_tenant(tenant_name, force_delete)
        if succ:
            dialog.accept()
            self.refresh(self.current_tenant_service)
        else:
            QMessageBox.warning(self, "删除失败", f"租户 {tenant_name} 删除失败")

    def on_item_double_clicked(self, item, column):
        if item is None:
            return
        item_text = item.text(0)
        item_data = item.data(0, Qt.UserRole)
        if item_data is None:
            return
        if item_data == "tenant":
            namespaces = self.get_namespaces(item_text)
            for namespace in namespaces:
                namespace_item = QTreeWidgetItem(item)
                namespace_item.setText(0, namespace)
                namespace_item.setData(0, Qt.UserRole, "namespace")
                topics = self.get_topics(namespace)
                for topic in topics:
                    topic_item = QTreeWidgetItem(namespace_item)
                    topic_item.setText(0, topic)
                    topic_item.setData(0, Qt.UserRole, "topic")
        if item_data == "namespace":
            namespace = item.text(0)
            topics = self.get_topics(namespace)
            for topic in topics:
                topic_item = QTreeWidgetItem()
                topic_item.setText(0, topic)
                topic_item.setData(0, Qt.UserRole, "topic")
        if item_data == "topic":
            #  persiste
            status_text = self.current_tenant_service.get_topic_status(item_text)
            self.main_content_area.refreshText(status_text)

    def get_namespaces(self, tenant):
        list_data = self.current_tenant_service.get_name_space(tenant)
        logger.info("{}", list_data)
        return list_data

    def get_topics(self, namespace):
        list_data = self.current_tenant_service.get_topics(namespace)
        logger.info("{}", list_data)
        return list_data
